﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.IO;

using Entity;

namespace SSLService
{
    public class sslIMAP
    {
        public static SslStream Connection(UserAccount _ua)
        {
            //NetworkStream _ns=new NetworkStream(    
            Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipdest = new IPEndPoint(System.Net.Dns.Resolve(_ua.ReciveServer).AddressList[0], _ua.ReciveServerPort);
            _socket.Connect(ipdest);
            NetworkStream _ns = new NetworkStream(_socket, true);
            _ns.ReadTimeout = 60000;
            //SslStream _sslStream = new SslStream(_ns,true ,);
            //_sslStream.AuthenticateAsClient("imap.gmail.com", new X509CertificateCollection(), SslProtocols.Default, true);
            SslStream _sslStream = new SslStream(_ns, false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
            _sslStream.AuthenticateAsClient(_ua.ReciveServer);

            StreamReader _sr = new StreamReader(_sslStream);

            string saff = _sr.ReadLine();
            ////login
            byte[] fff = System.Text.Encoding.Default.GetBytes("A1 LOGIN volkerzht VolkerZhang1982\r\n");
            _sslStream.Write(fff);

            saff = _sr.ReadLine();
            fff = System.Text.Encoding.Default.GetBytes("A1 LIST \"\" *\r\n");
            _sslStream.Write(fff);
            saff = _sr.ReadLine();
            saff = _sr.ReadLine();
            //saff = _sr.ReadToEnd();
            ////byte[] ssf = _br.ReadBytes(500);
            //saff = _sr.ReadLine();
            //string _ret = _sr.ReadLine();
            //_ret = _ret.TrimStart('*').TrimStart(' ');
            //if (_ret.StartsWith("OK"))
            //    return _sslStream;

            return null;
        }

        public static bool ValidateServerCertificate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            //Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
            throw new Exception(sslPolicyErrors.ToString());

            // Do not allow this client to communicate with unauthenticated servers.  
            return false;
        } 
    }
}
